<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>2-框选</title>
    <style>
      .selectBox {
        position: fixed;
        border: 1px solid #06c0fd;
        background-color: rgba(6, 192, 255, 0.3);
      }
    </style>
  </head>
  <body>
    <script>
      let startMouse = {}; // 按下时，鼠标坐标
      let select = null; // 记录元素
      // 鼠标移动的处理函数
      let move = (e) => {
        let nowMouse = {
          x: e.clientX,
          y: e.clientY,
        };
        let dis = {
          x: nowMouse.x - startMouse.x,
          y: nowMouse.y - startMouse.y,
        };
        // 框的宽度：两个坐标点的横向差值
        select.style.width = Math.abs(dis.x) + "px";
        // 框的高度：两个坐标点的纵向差值
        select.style.height = Math.abs(dis.y) + "px";
        // 框的left：两个坐标点靠近左侧的横坐标(较小的值)
        select.style.left = Math.min(nowMouse.x, startMouse.x) + "px";
        // 框的top：两个坐标点靠近上方的纵坐标(较小的值)
        select.style.top = Math.min(nowMouse.y, startMouse.y) + "px";
      };
      document.addEventListener("mousedown", (e) => {
        startMouse = {
          x: e.clientX,
          y: e.clientY,
        };
        select = document.createElement("div");
        select.className = "selectBox";
        document.body.appendChild(select);

        document.addEventListener("mousemove", move);
        document.addEventListener(
          "mouseup",
          () => {
            select.remove();
            document.removeEventListener("mousemove", move);
          },
          { once: true }
        );
      });
    </script>
  </body>
</html>
